package com.zipking.cloud.springbootmybatis.guava;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;

public class ListenableFutureDemo {
    /**
     * 执行任务器
     */
    private static ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());


    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args)throws Exception {
        ListenableFutureDemo demo=new ListenableFutureDemo();
        long beginTime = System.currentTimeMillis();
        System.out.println("begin："+beginTime);
        List<ListenableFuture<String>> futures = new ArrayList<ListenableFuture<String>>();
        futures.add(demo.getPackingTask("获取商品信息",1500));
        futures.add(demo.getPackingTask("获取商品扩展信息",1200));
        futures.add(demo.getPackingTask("获取库存信息",800));
        futures.addAll(demo.getDoublePackingTask(demo,"订单信息",1100,"订单明细",1200));
        System.out.println("================================================================================");
        // 阻塞三个线程执行完成
        Futures.allAsList(futures).get();
        long endTime = System.currentTimeMillis();
        System.out.println("end："+endTime);
        long uesdTime = endTime-beginTime;
        System.out.println("usedTime："+uesdTime);
        listeningExecutorService.shutdown();
    }


    /**
     * 执行任务
     */
    static class TaskInfo implements Callable<String> {
        /**
         * 任务名称
         */
        private String taskName;
        /**
         * 执行实际
         */
        private long executionTime;

        @Override
        public String call() throws Exception {
            System.out.println("taskName：" + taskName+"&线程名"+Thread.currentThread().getName());
            Thread.sleep(executionTime);
            return "任务名称"+taskName+"&执行时间"+executionTime;
        }
    }




    /**
     * 封装包装任务
     */
    public  ListenableFuture<String> getPackingTask(String taskName,long executionTime) {
        //创建一个线程实例
        ListenableFutureDemo.TaskInfo packingTask = new ListenableFutureDemo.TaskInfo();
        packingTask.taskName=taskName;
        packingTask.executionTime=executionTime;
        ListenableFuture<String> packingTaskfuture = listeningExecutorService.submit(packingTask);

        /**
         * FutureCallBack接口可以对每个任务的成功或失败单独做出响应
         */
        FutureCallback<String> futureCallback = new FutureCallback<String>() {
            /**
             * 返回成功后在调用商品扩展信息
             * @param result
             */
            @Override
            public void onSuccess(String result) {
                System.out.println("返回值：" + result+"&线程名"+Thread.currentThread().getName());
            }
            @Override
            public void onFailure(Throwable t) {
                System.out.println("返回值："+t.getMessage()+"&线程名"+Thread.currentThread().getName());
            }
        };

        /**
         * 执行回调函数的是主线程或执行任务的线程
         */
        Futures.addCallback(packingTaskfuture, futureCallback, MoreExecutors.directExecutor());
        return packingTaskfuture;
    }

    /**
     * 封装包装任务,包含子任务，既等父任务执行完，立马执行子任务
     */
    public List<ListenableFuture<String>> getDoublePackingTask(ListenableFutureDemo demo, String taskName, long executionTime, String childTaskName, long childExecutionTime) {
        List<ListenableFuture<String>> futures = new ArrayList<ListenableFuture<String>>();
        ListenableFutureDemo.TaskInfo packingTask = new ListenableFutureDemo.TaskInfo();
        packingTask.taskName = taskName;
        packingTask.executionTime = executionTime;
        ListenableFuture<String> packingTaskfuture = listeningExecutorService.submit(packingTask);
        /**
         * 监听器添加子任务
         */
        packingTaskfuture.addListener(() -> {
            futures.add(demo.getPackingTask(childTaskName, childExecutionTime));

        }, listeningExecutorService);

        futures.add(packingTaskfuture);
        return futures;
    }
}